const pool = require('./db');

class Room {
   async findById(roomId) {
    const [rows] = await pool.query('SELECT * FROM conference_room WHERE room_id = ?', [roomId]);
    return rows[0];
  }

   async findAll() {
    const [rows] = await pool.query('SELECT * FROM conference_room');
    return rows;
  }

   async filter({ type, seats, equipment, startTime, endTime }) {
    let query = 'SELECT * FROM conference_room WHERE status = "idle"';
    const params = [];
    
    if (type) {
      query += ' AND type = ?';
      params.push(type);
    }
    
    if (seats) {
      query += ' AND seats >= ?';
      params.push(seats);
    }
    
    if (equipment && equipment.length > 0) {
      equipment.forEach(item => {
        query += ' AND JSON_CONTAINS(equipment, ?)';
        params.push(JSON.stringify(item));
      });
    }
    
    // 检查时间冲突
    query += ' AND room_id NOT IN (SELECT room_id FROM `order` WHERE ' +
             '((start_time < ? AND end_time > ?) OR ' +
             '(start_time < ? AND end_time > ?) OR ' +
             '(start_time >= ? AND end_time <= ?)))';
    params.push(endTime, startTime, endTime, startTime, startTime, endTime);
    
    const [rows] = await pool.query(query, params);
    return rows;
  }

   async create(roomData) {
    const { room_name, type, area, seats, equipment, price, userId } = roomData;
    const [result] = await pool.query(
      'INSERT INTO conference_room (room_name, type, area, seats, equipment, price, admin_id) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [room_name, type, area, seats, JSON.stringify(equipment), price, userId]
    );
    return result.insertId;
  }

   async update(roomId, updateData) {
    const { room_name, type, area, seats, equipment, price } = updateData;
    await pool.query(
      'UPDATE conference_room SET room_name = ?, type = ?, area = ?, seats = ?, equipment = ?, price = ? WHERE room_id = ?',
      [room_name, type, area, seats, JSON.stringify(equipment), price, roomId]
    );
  }

   async delete(roomId) {
    await pool.query('DELETE FROM conference_room WHERE room_id = ?', [roomId]);
  }

   async updateStatus(roomId, status) {
    await pool.query('UPDATE conference_room SET status = ? WHERE room_id = ?', [status, roomId]);
  }
}

module.exports = new Room();